﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using OVS.BusinessObjects;
using OVS.BLL;
using System.Collections;
using MjpegProcessor;
using System.Diagnostics;
using OVS_FormsRecognition.Manager;
using Emgu.CV;
using Emgu.CV.Structure;
using System.Drawing;
using OVS_Tools;
using System.Windows.Threading;

namespace OVS_HaarConfigurator
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class HaarConfigurator : Window
    {
        public List<Image_Haar> _listObjects { get; set; }
        private MjpegDecoder _mjpeg;


        public HaarConfigurator()
        {
            InitializeComponent();

            InitialisHaarObjects();

            _mjpeg = new MjpegDecoder();
            _mjpeg.FrameReady += mjpeg_FrameReady;

            //  DispatcherTimer setup
            DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(ProcessFrame);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
        }

        private void mjpeg_FrameReady(object sender, FrameReadyEventArgs e)
        {

            _mjpeg.Bitmap = ImageHelper.GetBitmap(e.BitmapImage);
            //imageBox_Capture_Camera.Source = ImageHelper.CreateBitmapSourceFromBitmap(ProcessFrame(ImageHelper.GetBitmap(e.BitmapImage)));
            //imageBox_Capture_Camera.Source = e.BitmapImage;
        }

        private void ProcessFrame(object sender, EventArgs arg)
        {

            

            if (listBoxHaarObject.SelectedItem != null && (bool)checkBoxDetectObject.IsChecked && !isInDetectionMode && _mjpeg.Bitmap != null)
            {
                isInDetectionMode = true;
                int index = listBoxHaarObject.SelectedIndex;


                String HaartainningFileName = _listObjects[index].imha_fn;

                Image<Bgr, byte> frame = new Image<Bgr, byte>(_mjpeg.Bitmap);

                Image_Haar imageHaar = new Image_Haar();
                imageHaar.imha_fn = HaartainningFileName;

                //FormsRecognitionManager.Instance.ProcessGPUDetection(0, imageHaar, frame, 100, (double)SliderScalFactor.Value, (int)SliderMinNeighbors.Value, true);


                isInDetectionMode = false;
                imageBox_Capture_Camera.Source = ImageHelper.CreateBitmapSourceFromBitmap(frame.ToBitmap());

            }
            else
            {
                if (_mjpeg.Bitmap == null)
                    return;
                imageBox_Capture_Camera.Source = ImageHelper.CreateBitmapSourceFromBitmap(_mjpeg.Bitmap);
            }

        }


        /// <summary>
        /// Initialises the haar objects.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        private void InitialisHaarObjects()
        {
            try
            {
                _listObjects = Image_HaarBLL.Instance.GetImage_Haars();

                ArrayList itemsList = new ArrayList();


                foreach (Image_Haar item in _listObjects)
                {
                    itemsList.Add(item.imha_label);
                }

                listBoxHaarObject.ItemsSource = itemsList;
            }
            catch (Exception ex)
            {

                MessageBox.Show("Exception: " + ex);
            }
        }

        /// <summary>
        /// Handles the Click event of the button_Tester_Cam control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void button_Tester_Cam_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (button_Tester_Cam.Content.ToString() == "Tester")
                {
                    this.button_Tester_Cam.Content = "Stop";
                    _mjpeg.ParseStream(new Uri(Adresse_Ip.Text));
                    this.label_Resultat_Test.Content = "Connexion réussi";
                    this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Green);

                }
                else if (button_Tester_Cam.Content.ToString() == "Stop")
                {
                    button_Tester_Cam.Content = "Tester";
                    _mjpeg.StopStream();
                }
            }
            catch (Exception ex)
            {
                button_Tester_Cam.Content = "Tester";
                this.label_Resultat_Test.Content = "Impossible de se connecter à la caméra!!!";
                this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Red);

            }

        }

        private void listBoxHaarObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {

                if (_listObjects == null)
                    return;


                if (listBoxHaarObject.SelectedItem != null)
                {
                    int index = listBoxHaarObject.SelectedIndex;

                    SliderScalFactor.Value = Convert.ToDouble(_listObjects[index].imha_scaleFactor);

                    SliderMinNeighbors.Value = Convert.ToDouble(_listObjects[index].imha_minNeighbors);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("listBoxHaarObject_SelectionChanged: "+ ex.Message);
            }
        }



        public Stopwatch watch { get; set; }

        public bool isInDetectionMode { get; set; }

        private void SliderScalFactor_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (LabelScaleFactor == null)
                return;

            LabelScaleFactor.Content = String.Format("scaleFactor : {0:0.0}", SliderScalFactor.Value);
        }

        private void SliderMinNeighbors_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (LabelMinNeighbors == null)
                return;

            LabelMinNeighbors.Content = String.Format("minNeighbors : {0:0.0}", SliderMinNeighbors.Value);
        }

        private void buttonUpdateValues_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxHaarObject.SelectedItem != null)
            {
                int index = listBoxHaarObject.SelectedIndex;

                _listObjects[index].imha_scaleFactor = SliderScalFactor.Value;

                _listObjects[index].imha_minNeighbors = SliderMinNeighbors.Value;

                Image_HaarBLL.Instance.UpdateImage_Haar(_listObjects[index]);
            }
        }
    }
}
